package com.tuanchau.android.englishtooltip.ui.activity;

import java.util.LinkedList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.tuanchau.android.englishtooltip.R;
import com.tuanchau.android.englishtooltip.database.WordStruct;

public class ListWordAdapter extends ArrayAdapter<WordStruct> {

	private final LinkedList<WordStruct> list;
	private final Context context;

	public ListWordAdapter(Context context, LinkedList<WordStruct> list) {
		super(context, R.layout.activity_list_word_item, list);
		this.list = list;
		this.context = context;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			v = inflater.inflate(R.layout.activity_list_word_item, null);
		}

		WordStruct w = list.get(position);
		if (w != null) {
			TextView txtWord = (TextView) v
					.findViewById(R.id.activity_list_word_item_word);
			TextView txtMean = (TextView) v
					.findViewById(R.id.activity_list_word_item_mean);
			ImageView img = (ImageView) v
					.findViewById(R.id.activity_list_word_item_image);

			txtWord.setText(w.word);
			txtMean.setText(w.mean);
			if (w.bitmap != null) {
				img.setImageBitmap(w.bitmap);
			} else if (w.image != null) {
				
				Bitmap bitmap = BitmapFactory.decodeByteArray(w.image, 0, w.image.length);
				img.setImageBitmap(bitmap);
				w.bitmap = bitmap;
				
			} else {
				img.setImageResource(R.drawable.english_tip_icon_100);
			}
		}

		return v;
	}

	public void remove(int position) {
		if (position >= 0 && position < list.size())
			list.remove(position);
	}

	@Override
	public void add(WordStruct w) {
		list.add(w);
	}

	public WordStruct get(int position) {
		return list.get(position);
	}

	public int getLastId() {
		if(list.size() > 0)
			return list.getLast().id;
		else
			return 0;
	}

	public void edit(int position, String word, String type, String pron,
			String mean, byte [] image) {
		WordStruct w = list.get(position);
		w.word = word;
		w.type = type;
		w.pron = pron;
		w.mean = mean;
		w.image = image;
	}

	public int findIndexPosition(int index) {
		int length = list.size();
		for(int i = 0; i < length; i++) {
			WordStruct w = list.get(i);
			if(w.id == index) {
				return i;
			}
		}
		
		return -1;
	}

	@Override
	public int getCount() {
		return list.size();
	}
}